using System;
using Sustainalytics.ClientDW.Entities;
using Sustainalytics.Entities.ESGRatings;
using MongoDB.Driver;
using System.Threading.Tasks;

namespace Sustainalytics.ESGRatings.BusinessLogic
{
    public class DefaultReferenceUniverseProcessor
    {
        private readonly IMongoCollection<ReferenceUniverse> _referenceUniverseRepository;

        private readonly IMongoCollection<CorporateData> _corporateDataRepository;

        public DefaultReferenceUniverseProcessor(IMongoCollection<ReferenceUniverse> referenceUniverseRepository, IMongoCollection<CorporateData> corporateDataRepository)
        {
            _referenceUniverseRepository = referenceUniverseRepository;
            _corporateDataRepository = corporateDataRepository;
        }

        public async Task UpdateReferenceUniverseContent(Guid defaultReferenceUniverseId)
        {

            var companies = await _corporateDataRepository.Find(x => x.ComprehensiveEsgResearchState.ResearchState == BusinessResearchProductStates.Entities.ResearchState.ResearchState.ResearchAvailable)
                                    .Project(company => new ReferenceUniverseCompany(company.Id, company.CapitalIqId, company.CompanyName)).ToListAsync().ConfigureAwait(false);


            var defaultReferenceUniverse = await _referenceUniverseRepository.Find(x => x.Id == defaultReferenceUniverseId).FirstOrDefaultAsync().ConfigureAwait(false);

            if (defaultReferenceUniverse == null)
            {
                defaultReferenceUniverse = new ReferenceUniverse { Id = defaultReferenceUniverseId, Name = "Default", Companies = companies };
                await _referenceUniverseRepository.InsertOneAsync(defaultReferenceUniverse);
            }
            else
            {
                await _referenceUniverseRepository.UpdateOneAsync(u => u.Id == defaultReferenceUniverseId, Builders<ReferenceUniverse>.Update.Set(u => u.Companies, companies));
            }
        }
    }

}